from subsidy.app.utils.Utils import get_db_connection
from subsidy.app.utils import Utils
from subsidy.app.utils.JwtUtils import *
import datetime
from subsidy.app.utils.Md5Password import md5Password
from subsidy.app.mapper.BaseDB import BaseDb
class UserMapper(BaseDb):
    def __init__(self, logger=None):
        self.logger = logger
        super().__init__()
        self.connection.cursor()
        self.readsMapper = self.readDb

    def str_to_timestamp(self, datas:dict):
        """将datatime类型转换成字符串类型"""
        for key, val in datas.items():
            if isinstance(val, datetime.datetime):
                time = val.strftime('%Y-%m-%d %H:%M:%S')
                datas[key] = time
        return datas

    def checklogin(self, userInfo) -> dict:
        user = self.loginUser(userInfo)
        if user is not None:
            user = self.str_to_timestamp(user)
            token = generate_jwt(user)
            return {"status":200, "message": "登录成功", "data": {"token": token}}
        return {"status":302, "message": "登录失败！用户名或者密码错误。", "data": {"token": None}}

    def fondUserExit(self, userInfo):
        "判断用户是否存在"
        with self.connection.cursor() as cursor:
            selectOneUser = "SELECT * FROM user where username = %s"
            data = (userInfo.get("username"),)
            cursor.execute(selectOneUser, data)
            user = cursor.fetchone()
            return True if user is None else False

    def loginUser(self, userInfo):
        """查询登录"""
        user = None
        with self.connection.cursor() as cursor:
            loginSql = "SELECT * FROM user where username = %s and password = %s"

            data = (userInfo.get("username"),md5Password(userInfo.get("password")))
            cursor.execute(loginSql, data)
            user = cursor.fetchone()

        return user

    def registerUser(self, userInfo):
        try:
            with self.connection.cursor() as cursor:
                insertSql = "INSERT INTO user (id, nickname, username, password, del, is_active, is_superuser, created_at, updated_at, last_login) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"
                data = (Utils.getUuid(), "", userInfo.get("username"), md5Password(userInfo.get("password")), 0,
                    0, 0, Utils.getFormatted_datetime_now(), Utils.getFormatted_datetime_now(),
                    Utils.getFormatted_datetime_now())
                cursor.execute(insertSql, data)
                self.connection.commit()
            return True
        except Exception as e:
            print(e)
            return False


    def isLogger(self, type, *data):
        if self.logger is None:
            print(data)
        else:
            if type == "info":
                self.logger.info(f"数据库Info信息: {data}")
            else:
                self.logger.debug(f"数据库Info信息: {data}")



    def querAllClassInfo(self, idCar):
        """查询全部课程进度"""
        try:
            # 先检查数据库连接是否正常
            test_cursor = self.connection.cursor()
            test_query = "SELECT 1"
            test_cursor.execute(test_query)
            test_result = test_cursor.fetchone()
            if test_result is None:
                raise Exception("数据库连接可能异常，请检查连接设置。")
            test_cursor.close()

            # 创建游标
            print(idCar)
            cursor = self.connection.cursor()
            sql = "SELECT * FROM progress_video where idCar = %s"
            cursor.execute(sql, (idCar,))
            results = cursor.fetchall()
            results = [result for result in results]
            self.isLogger("info", f"查询成功：{results}, 共{len(results)}条数据")
            return results
        except Exception as e:
            print(e)
            self.isLogger("debug", f"查询出错：{e}")
        finally:
            # 关闭游标
            cursor.close()





    def setIdentityMapper(self, data:dict):
        """绑定账号"""
        try:
            print(data)
            cursor = self.connection.cursor()
            sql = "INSERT INTO myidentity (id, idCar, password) VALUES (%s, %s, %s)"
            print("sql=========", sql)
            cursor.execute(sql, (data.get("id"), data.get("idCar"), data.get("password")))
            self.connection.commit()
            self.isLogger("info", f"用户 {data['idCar']} 的数据已成功插入。")
        except Exception as e:
            print(f"插入用户信息时出错: {e}")
            self.connection.rollback()
        finally:
            cursor.close()

    def quryIdentityMapper(self, data):
        """查找绑定账号"""
        try:
            cursor = self.connection.cursor()
            sql = "SELECT * FROM myidentity where id = %s and idCar = %s"
            cursor.execute(sql, (data.get("id"), data.get("idCar")))
            result = cursor.fetchone()
            self.isLogger("info", f"用户 {data.get('idCar')} 的数据已成功查询。")
            return result
        except Exception as e:
            print(f"查询用户信息时出错: {e}")
        finally:
            cursor.close()

    def delIdentityMapper(self, data):
        """根据id删除绑定信息"""
        try:
            cursor = self.connection.cursor()
            sql = "DELETE FROM myidentity WHERE id = %s"
            cursor.execute(sql, (data.get("id"),))
            self.connection.commit()
            self.isLogger("info", f"用户 {data.get('id')} 的绑定信息删除成功。")
            return True
        except Exception as e:
            print(f"更新用户信息时出错: {e}")
            # 回滚事务
            self.connection.rollback()
        finally:
            cursor.close()